package jmind.core.support;

import java.io.IOException;
import java.util.*;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;

import com.google.common.collect.Lists;
import jmind.base.util.DataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class DocumentUtil {

    private static Map<String, Document> map = new ConcurrentHashMap<>();

    public static Document getDoc(String name) {
        if (map.containsKey(name)) {
            return map.get(name);
        }
        Document doc = initDoc(name);
        map.put(name, doc);
        return doc;

    }

    private static Document initDoc(String name) {
        try {
            return Jsoup.parse(DocumentUtil.class.getClassLoader().getResourceAsStream(name), "UTF-8", "");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param xml
     * @param tag
     * a b 在给定的祖先元素下匹配所有的后代元素
     * a >b  在给定的父元素下匹配所有的子元素
       a +b 匹配所有紧接在 prev 元素后的 next 元素
    prev ~ siblings 匹配 prev 元素之后的所有 siblings 元素
     * @return
     */
    public static List<String> getTagValues(String xml, String tag) {
        if(DataUtil.isEmpty(xml))
            return Collections.emptyList();
        List<String> list = Lists.newArrayList();
        Elements elements = Jsoup.parse(xml).select(tag);
        for (Element ele : elements) {
            list.add(ele.text());
        }
        return list;
    }


    public static String getTagValue(String xml, String tag) {
        if(DataUtil.isEmpty(xml))
            return  DataUtil.EMPTY;
        return Jsoup.parseBodyFragment(xml).select(tag).text();
    }



    public static void main(String[] args) {
        String values = getTagValue("<a><b>sds</b><d>sd</d></a>", "a >b");

        System.out.println(values);

    }

}
